import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:common_lib/common_compoent.dart';
import 'package:doctor_prescribe_lib/diagnostic_result/diagnostic_result_widget.dart';
import 'package:doctor_prescribe_lib/doctor_prescribe_component.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'bloc.dart';
import 'package:fsuper/fsuper.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientBean;

///线下处方基本信息
class OfflineBasicInfoPage
    extends BaseBlocPage<OfflineBasicInfoBloc, _PageState> {
  OfflineBasicInfoPage(Parameters parameters) : super(parameters);

  @override
  _PageState generateThemeState() {
    return _PageState();
  }
}

class _PageState extends BaseBlocPageState<OfflineBasicInfoBloc> {
  var titleTextStyle = TextStyle(fontSize: 15, color: Colors.black);
  var hintTextStyle = TextStyle(fontSize: 13, color: Colors.grey);

  ///  rxType: 0, // 选中的处方类型：0西药, 1中药
  int rxType = 0;

  @override
  void initState() {
    rxType = parameters.getInt('rxType') ?? 0;
    bloc.doInit(rxType, parameters.getInt('medicineFormID') ?? 0);
    super.initState();
  }

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        title: Text(parameters.getString('title') ?? '基本信息'),
        centerTitle: true,
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: SingleChildScrollView(
          child: Column(
            children: [
              buildPersonInfo(titleTextStyle, hintTextStyle, theme),
              buildAddress(titleTextStyle, hintTextStyle, theme),
              buildAddressDetail(titleTextStyle, hintTextStyle, theme),
              buildDiagnosticResult(titleTextStyle, hintTextStyle, theme),
              20.vGapDp,
              rxType == 0
                  ? buildSicknessInfo(titleTextStyle, hintTextStyle, theme)
                  : SizedBox(),
              20.vGapDp,
              FSuper(
                onClick: () {
                  nextHandler(theme);
                },
                width: double.infinity,
                height: 45,
                backgroundColor: theme.themeColor.themeColor,
                margin: EdgeInsets.all(15),
                child1: Text(
                  '下一步',
                  style: TextStyle(color: Colors.white),
                ),
                corner: Corner.all(15),
              ),
              20.vGapDp,
            ],
          ),
        ),
      ),
    );
  }

  Widget buildPersonInfo(
      TextStyle titleTextStyle, TextStyle hintTextStyle, MTheme theme) {
    return Column(
      children: [
        1.gapV(Colors.grey[350]),
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(top: 10),
          child: Text(
            '就诊人信息',
            style: titleTextStyle,
          ),
        ),
        Row(
          children: [
            StreamBuilder(
              stream: bloc.patientSubject,
              builder: (context, AsyncSnapshot<PatientBean.Datum> snapshot) {
                if (snapshot.hasData) {
                  bloc.setAddressResult(AddressResult(
                    provinceName: snapshot.data.province,
                    provinceId: snapshot.data.provinceCode,
                    cityName: snapshot.data.city,
                    cityId: snapshot.data.cityCode,
                    areaName: snapshot.data.area,
                    areaId: snapshot.data.areaCode,
                  ));

                  bloc.setDetailAddress(snapshot.data.address);
                }
                return Text(
                  snapshot.hasData ? snapshot.data.patientName : '添加就诊人',
                  style: hintTextStyle,
                );
              },
            ),
            Spacer(),
            IconButton(
              onPressed: () {
                FocusScope.of(context).unfocus();
                bloc.addPatient(context);
              },
              iconSize: 15,
              icon: Icon(
                Icons.arrow_forward_ios,
                color: Colors.grey,
              ),
            ),
          ],
        ),
        1.gapV(Colors.grey[350]),
      ],
    );
  }

  Widget buildAddress(
      TextStyle titleTextStyle, TextStyle hintTextStyle, MTheme theme) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(top: 10),
          child: Text(
            '地区',
            style: titleTextStyle,
          ),
        ),
        StreamBuilder(
            stream: bloc.addressResultSubject,
            builder: (context, AsyncSnapshot<AddressResult> snapshot) {
              return Row(
                children: [
                  Text(
                    snapshot.hasData
                        ? '${snapshot.data.provinceName} ${snapshot.data.cityName ?? ''} ${snapshot.data.areaName ?? ''}'
                        : '点击右侧按钮选择地址',
                    style: hintTextStyle,
                  ),
                  Spacer(),
                  IconButton(
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      var addressResult = await AddressPicker.showAddressPicker(
                          locationCode: snapshot.data?.areaId ?? null,
                          context: context,
                          height: 200);
                      bloc.setAddressResult(addressResult);
                    },
                    iconSize: 15,
                    icon: Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                    ),
                  ),
                ],
              );
            }),
        1.gapV(Colors.grey[350]),
      ],
    );
  }

  Widget buildAddressDetail(
      TextStyle titleTextStyle, TextStyle hintTextStyle, MTheme theme) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(top: 10),
          child: Text(
            '详细地址',
            style: titleTextStyle,
          ),
        ),
        20.vGapDp,
        Container(
          padding: EdgeInsets.all(5),
          decoration: BoxDecoration(
              color: Colors.grey[200], borderRadius: BorderRadius.circular(5)),
          height: 120,
          child: StreamBuilder(
            stream: bloc.detailAddressSubject,
            builder: (context, AsyncSnapshot<String> snapshot) {
              return TextField(
                textInputAction: TextInputAction.done,
                onChanged: (str) {
                  bloc.setDetailAddress(str);
                },
                controller: TextEditingController(
                    text: snapshot.hasData ? snapshot.data : ''),
                decoration: InputDecoration(
                    hintText: '请输入详细地址...',
                    hintStyle: hintTextStyle,
                    border: InputBorder.none),
              );
            },
          ),
        ),
        20.vGapDp,
        1.gapV(Colors.grey[350]),
        20.vGapDp,
      ],
    );
  }

  Widget buildDiagnosticResult(
      TextStyle titleTextStyle, TextStyle hintTextStyle, MTheme theme) {
    return DiagnosticResultWidget((list) {
      bloc.setDiagnosticResult(list);
    });
  }

  buildSicknessInfo(
      TextStyle titleTextStyle, TextStyle hintTextStyle, MTheme theme) {
    return StreamBuilder(
      stream: bloc.patientSubject,
      builder: (context, AsyncSnapshot<PatientBean.Datum> snapshot) {
        var def = snapshot.hasData
            ? SicknessResult(
                snapshot.data.historyOfAllergy,
                snapshot.data.allergyDetail,
                snapshot.data.historyOfSickness,
                snapshot.data.sicknessDetail,
                snapshot.data.liver,
                snapshot.data.renal,
                snapshot.data.pregnancy)
            : null;
        return snapshot.hasData
            ? SicknessInfoWidget(
                (sickness) {
                  FocusScope.of(context).unfocus();
                  bloc.setSicknessInfo(sickness);
                },
                defValue: def,
                isFemale: snapshot.data.sex == 2,
              )
            : SizedBox();
      },
    );
  }

  void nextHandler(MTheme theme) {
    FocusScope.of(context).unfocus();
    bloc.next(context, rxType,
        inquiryID: parameters.getInt('inquiryID'),
        personID: parameters.getInt('personID'));
  }

  @override
  OfflineBasicInfoBloc generateBloc() {
    return OfflineBasicInfoBloc();
  }
}
